<?php
namespace Logic\Member;
use Spartan\Lib\Logic;

!defined('APP_PATH') && exit('404 Not Found');

/**
 * 用户的资金操作
 * Class UserAccount
 * @package Logic\Member
 */
class UserAccount extends Logic
{
    private $_userId = 0;//用户ID
    private $_busId = 0;//操作的外接ID。
    private $_arrAmount = Array();//待操作数量
    private $_arrAccountType = Array();//帐号的消费类型
    private $_arrPayment = Array();
    private $_arrData = Array();//待更新的字段
    private $_arrContent = Array();//各个操作的备注
    private $arrField = Array(
        'spending'=>Array(1,'total_','-','use_','-'),//支出
        'income'=>Array(2,'total_','+','use_','+'),//收入
        'lock'=>Array(3,'use_','-','lock_','+'),//锁定
        'unlock'=>Array(4,'use_','+','lock_','-'),//解锁
        'lock_pay'=>Array(1,'total_','-','lock_','-'),//锁付
    );
    private $arrAccountType = Array(
        'recharge'=>Array(1,'充值'),
        'withdraw'=>Array(2,'提现'),
        'reward'=>Array(3,'奖励'),
        'vip'=>Array(4,'购买Vip'),
        'order'=>Array(5,'订单支付'),
    );

    /**
     * @param int $intUserId
     * @param int $busId
     * @return \Logic\Member\UserAccount
     */
    public function setUser($intUserId=0,$busId=0){
        $this->_arrAccountType = Array();
        $this->_arrPayment = Array();
        $this->_arrAmount = Array();
        $this->_arrData = Array();
        $this->_arrContent = Array();
        $this->_userId = $intUserId;
        $this->_busId = $busId;
        return $this;
    }

    /**
     * 设置金钱
     * @param int $amount
     * @param $payment
     * @param $accountType
     * @param string $content
     * @return \Logic\Member\UserAccount
     */
    public function setGold($amount=0,$payment,$accountType,$content=''){
        $this->_arrAmount['gold'] = max(0,$amount);
        $this->_arrContent['gold'] = $content;
        $this->_getUpdateField($payment,$accountType,'gold',$amount);
        return $this;
    }
    /**
     * 设置积分
     * @param int $amount
     * @param $payment
     * @param string $accountType
     * @param string $content
     * @return \Logic\Member\UserAccount
     */
    public function setScore($amount=0,$payment,$accountType='',$content=''){
        $this->_arrAmount['score'] = max(0,$amount);
        $this->_arrContent['score'] = $content;
        $this->_getUpdateField($payment,$accountType,'score',$amount);
        return $this;
    }
    /**
     * 设置不可提现金额
     * @param int $amount
     * @param $payment
     * @param string $accountType
     * @param string $content
     * @return \Logic\Member\UserAccount
     */
    public function setDiam($amount=0,$payment,$accountType='',$content=''){
        $this->_arrAmount['diam'] = max(0,$amount);
        $this->_arrContent['diam'] = $content;
        $this->_getUpdateField($payment,$accountType,'diam',$amount);
        return $this;
    }

    /**
     * 设置其它字段信息
     * @param $field
     * @param $amount
     * @param string $type
     * @return \Logic\Member\UserAccount
     */
    public function setField($field,$amount,$type='add'){
        $this->_arrData[$field] = Array('exp',$field.'+'.($type=='add'?$amount:0-$amount));
        return $this;
    }

    /**
     * 取得一个支付方式
     * @param $intId
     * @return string
     */
    public function getPayment($intId){
        foreach($this->arrField as $key=>$value){
            if ($value[0] == $intId){
                return $key;
            }
        }
        return 'unkown';
    }

    /**
     * 取得一个流水方式
     * @param $intId
     * @return string
     */
    public function getAccountType($intId){
        foreach($this->arrAccountType as $value){
            if ($value[0] == $intId){
                return $value[1];
            }
        }
        return 'unkown';
    }
    //各种结算方式 需要更新的字段。找出payment,account_type
    private function _getUpdateField($payment,$accountType,$strField='gold',$amount=0){
        if (!isset($this->arrField[$payment])){
            print_r("支付方式“{$payment}”不存在");die();
        }
        $this->_arrPayment[$strField] = $this->arrField[$payment][0];
        if (!isset($this->arrAccountType[$accountType])){
            print_r("帐目类型“{$accountType}”不存在");die();
        }
        $this->_arrAccountType[$strField] = $this->arrAccountType[$accountType][0];
        //更新的字段构成
        $temp = $this->arrField[$payment];
        $temp = Array(
            $temp[1].$strField=>Array('exp',$temp[1].$strField.$temp[2].$amount),
            $temp[3].$strField=>Array('exp',$temp[3].$strField.$temp[4].$amount),
        );
        $this->_arrData = $this->_arrData?array_merge($this->_arrData,$temp):$temp;
    }
    //更新动作
    public function update(){
        if (!$this->_userId){
            return Array('用户ID不能为空。',0);
        }
        if (!$this->_busId){
            return Array('外接ID不能为空。',0);
        }
        if (array_sum($this->_arrAmount) <= 0){
            return Array('更新数据全为0。',0);
        }
        if (!$this->_arrData){
            return Array('没有需要操作的字段。',0);
        }
        $options = Array(
            'where'=>Array(
                'user_id'=>$this->_userId,
            ),
        );
        $this->Db()->startTrans('UserAccount.update');
        $this->_arrData['update_time'] = date('Y-m-d H:i:s',time());
        $result = $this->Db()->update('member_account',$this->_arrData,$options);

        if ($result === false) {
            $this->Db()->rollback();
            return Array($this->_userId."帐户资金更新失败:".$this->Db()->getError(),0);
        }
        //检测帐号是否正常
        $options = Array(
            'where'=>Array(
                'user_id'=>$this->_userId,
            ),
            'lock'=>true,
        );
        $arrAccountInfo = $this->Db()->find('member_account',$options);
        foreach($arrAccountInfo as $k => $v){
            if ($v < 0){
                $this->Db()->rollback();
                return Array($this->_userId."帐户资金异常，无法继续操作。{$k}={$v}",0);
            }
        }
        //以下是更新各种操作的字段
        $arrData = Array(
            'user_id'=>$this->_userId,
            'ip'=> $this->clsRequest->getClientIp(),
            'add_time'=> date('Y-m-d H:i:s',time()),
            'business_id'=>$this->_busId,
        );
        $arrTemp = $arrResult = Array();
        //更新帐户余额
        if (isset($this->_arrAmount['gold']) && $this->_arrAmount['gold'] > 0){
            $arrTemp['account_type'] = $this->_arrAccountType['gold'];
            $arrTemp['payment'] = $this->_arrPayment['gold'];
            $arrTemp['amount'] = $this->_arrAmount['gold'];
            $arrTemp['content'] = $this->_arrContent['gold'];
            $arrTemp['current_total']= $arrAccountInfo['total_gold'];
            $arrTemp['current_use']= $arrAccountInfo['use_gold'];
            $arrTemp['current_lock']= $arrAccountInfo['lock_gold'];
            $arrTemp['log_type'] = 1;//金币，gold
            $result = $this->Db()->insert('member_account_log',array_merge($arrData,$arrTemp));
            if ($result == false){
                $this->Db()->rollback();
                $this->sysError();
                return Array($this->_userId."添加帐户1日志失败:".$this->Db()->getError(),0);
            }
            $arrResult[] = max(0,$result);
        }
        //更新帐户积分
        if (isset($this->_arrAmount['score']) && $this->_arrAmount['score'] > 0){
            $arrTemp['account_type'] = $this->_arrAccountType['score'];
            $arrTemp['payment'] = $this->_arrPayment['score'];
            $arrTemp['amount'] = $this->_arrAmount['score'];
            $arrTemp['content'] = $this->_arrContent['score'];
            $arrTemp['current_total']= $arrAccountInfo['total_score'];
            $arrTemp['current_use']= $arrAccountInfo['use_score'];
            $arrTemp['current_lock']= $arrAccountInfo['lock_score'];
            $arrTemp['log_type'] = 2;//积分
            $result = $this->Db()->insert('member_account_log',array_merge($arrData,$arrTemp));
            if ($result == false){
                $this->Db()->rollback();
                $this->sysError();
                return Array($this->_userId."添加帐户2日志失败:".$this->Db()->getError(),0);
            }
            $arrResult[] = max(0,$result);
        }
        //更新不可提现金额
        if (isset($this->_arrAmount['diam']) && $this->_arrAmount['diam'] > 0){
            $arrTemp = [];
            $arrTemp['account_type'] = $this->_arrAccountType['diam'];
            $arrTemp['payment'] = $this->_arrPayment['diam'];
            $arrTemp['amount'] = $this->_arrAmount['diam'];
            $arrTemp['content'] = $this->_arrContent['diam'];
            $arrTemp['current_total']= $arrAccountInfo['total_diam'];
            $arrTemp['current_use']= $arrAccountInfo['use_diam'];
            $arrTemp['current_lock']= $arrAccountInfo['lock_diam'];
            $arrTemp['log_type'] = 3;//钻石
            $result = $this->Db()->insert('member_account_log',array_merge($arrData,$arrTemp));
            if ($result == false){
                $this->Db()->rollback();
                $this->sysError();
                return Array($this->_userId."添加帐户3日志失败:".$this->Db()->getError(),0);
            }
            $arrResult[] = max(0,$result);
        }
        //添加帐户系统日志，后期可以取消
        $arrSysData = Array(
            'account_log_id'=>implode(',',$arrResult),
            'content'=>implode('@@',$this->_arrContent),
            'add_time'=> date('Y-m-d H:i:s',time()),
            'user_id'=>$arrAccountInfo['user_id'],
            'field_content' => str_replace('"exp",','',json_encode($this->_arrData,JSON_UNESCAPED_UNICODE)),
            'value_content' => json_encode(
                Array(
                    'total_gold'=>$arrAccountInfo['total_gold'],
                    'use_gold'=>$arrAccountInfo['use_gold'],
                    'lock_gold'=>$arrAccountInfo['lock_gold'],
                    'total_score'=>$arrAccountInfo['total_score'],
                    'use_score'=>$arrAccountInfo['use_score'],
                    'lock_score'=>$arrAccountInfo['lock_score'],
                    'total_diam'=>$arrAccountInfo['total_diam'],
                    'use_diam'=>$arrAccountInfo['use_diam'],
                ),JSON_UNESCAPED_UNICODE),
        );
        $result = $this->Db()->insert('member_account_sys_log',$arrSysData);
        if ($result == false){
            $this->Db()->rollback();
            $this->sysError();
            return Array($this->_userId.'添加帐户系统日志失败:'.$this->Db()->getError(),0);
        }
        $arrAccountInfo['sys_id'] = $result;
        $this->Db()->commit('UserAccount.update');
        return Array('更新成功。',1,$arrAccountInfo);
    }

    public function find(){
        $intUserId = max(0,$this->getData('user_id'));
        if ($intUserId < 1){
            return Array('ID为空。',0);
        }
        $options = Array(
            'where'=>Array(
                'user_id'=>$intUserId,
            )
        );
        $arrInfo = $this->Db()->find('member_account',$options);
        if (!$arrInfo){
            return Array('没有找到相应的用户。',0);
        }
        return Array('ok',1,$arrInfo);
    }
}